package project.euler.honk.problem.to50;

public final class Problem50 {

	private static final int[] primes = new int[100000];
	private static int current = 1;
	private static int currentN = 3;

	static {
		primes[0] = 2;
	}

	private static boolean isPrime(int number) {
		if (number == 1)
			return false;
		int max = (int) Math.sqrt(number);
		for (int i = 2; i <= max; i++)
			if (number % i == 0)
				return false;
		return true;
	}	

	private static int getPrime(int index) {
		while (index >= current) {
			while (!isPrime(currentN))
				currentN++;
			primes[current] = currentN;
			currentN += 2;
			current++;
		}
		return primes[index];
	}

	public static int solve() {
		int max = 0;
		int maxSum = 0;
		final int LIMIT = 1000000;
		for (int i = 0;; i++) {
			int sum = getPrime(i);
			if (sum >= LIMIT)
				break;
			for (int j = i + 1;; j++) {
				int prime = getPrime(j);
				sum += prime;
				if (sum >= LIMIT)
					break;
				if (isPrime(sum)) {
					if (max < (j - i + 1)) {
						max = (j - i + 1);
						maxSum = sum;
					}
				}
			}
		}
		return maxSum;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		long result = solve();
		long end = System.currentTimeMillis();
		System.out.println("Result: " + result + " Time: " + (end - start));
	}

}
